<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车模块</title>
    <style>
        table{
            width: 100%;
            border-collapse: collapse;  /*合并表格边框，使相邻单元格的边框合并为一条，看起来更整洁*/
        }
        th,td{
            border: 1px solid #ddd;
            padding: 8px;  /*内容与边框的*/
            text-align: left;
        }
        th{
            background-color: #4caf50;
            color: white;
        }
        button{
            background-color:#f44336;
            color: white;
            padding: 8px 16px;
            border:none;
            cursor: pointer;
        }
        button:hover{
            background-color: #d32f2f;
        }

    </style>
</head>
<body>
    <h2>购物车</h2>
    <table id="cart">
        <tr>
            <th>商品名称</th>
            <th>价格</th>
            <th>数量</th>
            <th>操作</th>
        </tr>
        <tr>
            <td>苹果</td>
            <td>5元</td>
            <td><input type="number" value="1"></td>
            <td><button>删除</button></td>
        </tr>
        <tr>
            <td>香蕉</td>
            <td>3元</td>
            <td><input type="number" value="2"></td>
            <td><button>删除</button></td>
        </tr>
    </table>
    <p>总价:<span id="totalPrice">0</span></p>
    <script>
        //获取相关元素
        const cartTable = document.getElementById('cart');
        const totalPriceSpan = document.getElementById('totalPrice');

        //计算总价的函数
        function calculateTotalPrice(){
            let total = 0;
            const rows = cartTable.rows;
            for(let i = 1; i < rows.length; i++){
                //从第二行开始，因为第一行是表头
                const priceCell = rows[i].cells[1].textContent;
                //获取价格单元格的文本
                const quantityCell = rows[i].cells[2].querySelector('input').value;
                //获取数量输入框的值
                const price = parseFloat(priceCell.replace('元',''));
                //提取价格数字
                const quantity = parseInt(quantityCell);
                //提供数量数字
                total += price * quantity;
                //计算总价
            }
            //显示总价的，保留两位小数
            totalPriceSpan.textContent = total.toFixed(2) + '元';
        }

        //为数量输入框添加输入事件监听
        for(let i = 1; i < cartTable.rows.length; i++){
            const quantityInput = cartTable.rows[i].cells[2].querySelector('input');
            quantityInput.addEventListener('input',calculateTotalPrice);
        }

        //为删除按钮添加点击事件监听
        for(let i = 1; i < cartTable.rows.length; i++){
            const deleteButton = cartTable.rows[i].cells[3].querySelector('button');
            deleteButton.addEventListener('click',function(){
                //删除当前行
                cartTable.deleteRow(i);
                //重新计算总价
                calculateTotalPrice();
            })
        }

        //初始计算总价
        calculateTotalPrice();
    </script>
</body>
</html>